package rewind.show.es.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.ElasticsearchIndicesClient;
import co.elastic.clients.elasticsearch.indices.ExistsRequest;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import co.elastic.clients.util.ObjectBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import rewind.show.es.anno.EsDocument;
import rewind.show.es.anno.EsField;
import rewind.show.es.exception.EsException;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.function.Function;

@Service
public class EsIndexServiceImpl {

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    public void save(Class<?> clazz) throws IOException {

        EsDocument esDocument = clazz.getAnnotation(EsDocument.class);
        if (esDocument == null) {
            throw new EsException(String.format("%s is not annotated with @EsDocument", clazz.getName()));
        }

        // 索引,从注解配置上获取,没有则取类名
        String index = StringUtils.isEmpty(esDocument.index()) ? clazz.getSimpleName() : esDocument.index();

        // 校验索引是否存在,不存在则新增
        ElasticsearchIndicesClient indicesClient = elasticsearchClient.indices();
        BooleanResponse existsResponse = indicesClient.exists(new ExistsRequest.Builder().index(Collections.singletonList(index)).build());
        boolean result = existsResponse.value();


        // 遍历所有字段,生成ES字段映射
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            EsField esField = field.getAnnotation(EsField.class);
            if (esField == null) {
                continue;
            }


            /*Function<TypeMapping.Builder, ObjectBuilder<TypeMapping>> typeMappingFunc = x -> {
                x.properties(StringUtils.isEmpty(esField.name()) ? field.getName() : esField.name(), );
            };*/
        }


        indicesClient.create(x -> {
            x.index(index);
            x.mappings(m -> m
                    .properties("title", p -> p.text(t -> t.analyzer("ik_max_word")  // 使用IK分词器（需提前安装）
                            .fields("keyword", f -> f.keyword(k -> k))  // 同时存储keyword子字段用于聚合
                    ))
                    .properties("publishTime", p -> p.date(d -> d
                            .format("yyyy-MM-dd HH:mm:ss")  // 指定日期格式
                    ))
                    .properties("views", p -> p.integer(i -> i))  // 明确为整数类型
            );
            return x;
        });
    }
}